<?php
/**
 * @copyright ©2018 北京麦盟科技
 * @author Lu Wei
 * @link http://www.bjmaimeng.com/
 * Created by IntelliJ IDEA
 * Date Time: 2019/1/16 11:21
 */


namespace app\forms\api\order;


use app\models\User;
use app\models\Goods;
use app\models\Share;
use app\models\UserInfo;
use app\models\OrderDetail;
use app\models\ShareBuyLog;
use app\models\ShareSetting;
use app\models\UserIdentity;
use app\models\GoodsCatRelation;
use app\core\payment\PaymentNotify;
use app\core\payment\PaymentOrder;
use app\events\OrderEvent;
use app\models\Model;
use app\models\Order;
use app\models\OrderVipCardInfo;
use app\plugins\vip_card\forms\common\CommonVip;
use app\plugins\vip_card\models\VipCard;
use app\plugins\vip_card\models\VipCardDetail;
use app\plugins\vip_card\models\VipCardDiscount;

class OrderPayNotify extends PaymentNotify
{

    /**
     * @param PaymentOrder $paymentOrder
     * @return mixed
     */
    public function notify($paymentOrder)
    {
        $order = Order::findOne([
            'order_no' => $paymentOrder->orderNo,
        ]);
        if (!$order) {
            return false;
        }
        $order->is_pay = 1;
        switch ($paymentOrder->payType) {
            case PaymentOrder::PAY_TYPE_HUODAO:
                $order->is_pay = 0;
                $order->pay_type = 2;
                break;
            case PaymentOrder::PAY_TYPE_BALANCE:
                $order->pay_type = 3;
                break;
            case PaymentOrder::PAY_TYPE_ALIPAY:
            case PaymentOrder::PAY_TYPE_BAIDU:
            case PaymentOrder::PAY_TYPE_TOUTIAO:
            case PaymentOrder::PAY_TYPE_WECHAT:
            case PaymentOrder::PAY_TYPE_WECHAT_H5:
            case PaymentOrder::PAY_TYPE_ALIPAY_H5:
            case PaymentOrder::PAY_TYPE_UNIONPAY:
            case PaymentOrder::PAY_TYPE_WECHAT_SCAN:
            case PaymentOrder::PAY_TYPE_ALIPAY_SCAN:
                $order->pay_type = 1;
                break;
            case PaymentOrder::PAY_TYPE_CASH:
                $order->pay_type = 4;
                break;
            case PaymentOrder::PAY_TYPE_POS:
                $order->pay_type = 5;
                break;
            default:
                break;
        }
        $order->pay_time = date('Y-m-d H:i:s');
        $this->setVipCardPrice($order, $paymentOrder);
        $order->save();

        $ids = OrderDetail::findAll(['order_id' => $order->id]);
        \Yii::error('$ids--->>>>');
        \Yii::error(json_encode($ids, 256));
        $ids2 = Goods::find()->where(['in', 'id', array_column($ids, 'goods_id')])->asArray()->all();
        \Yii::error('ids2--->>>>');
        \Yii::error(json_encode($ids2, 256));

        $setting = ShareSetting::find()
            ->where(['in', 'key', ['become_condition', 'share_goods_status', 'share_goods_warehouse_id', 'cat_list']])
            ->where(['mall_id' => $order->mall_id])
            ->asArray()
            ->all();
        $setting = array_column($setting, null, 'key');
        \Yii::error('$setting--->>>>');
        \Yii::error(json_encode($setting, 256));
        foreach ($ids2 as $v) {
            $catRelation = GoodsCatRelation::find()->where(['goods_warehouse_id' => $v['goods_warehouse_id']])->one()->toArray();
            \Yii::error('$catRelation--->>>>');
            \Yii::error(json_encode($catRelation, 256));

            $flag = false;
            if ($setting['become_condition']['value'] == 2) {
                switch ($setting['share_goods_status']['value']) {
                    case 1:
                        $flag = true;
                        break;
                    case 2:
                        if (in_array($v['goods_warehouse_id'], json_decode($setting['share_goods_warehouse_id']['value'], true))) {
                            $flag = true;
                        }
                        break;
                    case 3:
                        if (in_array($catRelation['cat_id'], json_decode($setting['cat_list']['value'], true))) {
                            $flag = true;
                        }
                        break;
                }
            }
            \Yii::error("是分销商品?:" . (int)$flag);

            if ($flag) {
                $shareModel = Share::find()->where([
                    'user_id' => $order->user_id,
                    'status' => 1
                ])->one();
                \Yii::error('$shareModel--->>>>');
                \Yii::error($shareModel ? json_encode($shareModel->toArray(), 256) : '$shareModel not exist');
                if (!$shareModel) {
                    \Yii::error('!$shareModel--->>>>');
                    $shareModel = new Share();
                    $shareModel->mall_id = $order->mall_id;
                    $shareModel->user_id = $order->user_id;
                    $shareModel->status = 1;
                    $shareModel->is_delete = 0;
                    $shareModel->apply_at = date('Y-m-d H:i:s');
                    $res = $shareModel->save();
                    \Yii::error('$shareModel->save() res--->>>>' . (int)$res);

                    $idModel = UserIdentity::find()->where(['user_id' => $order->user_id])->one();
                    $idModel->is_distributor = 1;
                    $idModel->save();
                }
                $s_id = $shareModel->id;
                \Yii::error('$s_id--->>>>' . $s_id);

                $headers = \Yii::$app->request->headers;
                $userId = empty($headers['x-user-id']) ? null : $headers['x-user-id'];
//                $userId = 426;//todo
                \Yii::error('$userId--->>>>' . $userId);
                $parent_user_id = $parent_share_id = 0;
                if ($userId) {
                    $t = ShareBuyLog::find()
                        ->where(['user_id' => $userId, 'goods_id' => $v['id']])
                        ->all();
                    if ($t) {
                        $share = Share::find()->where(['user_id' => $userId])->one();
                        $parent_user_id = $userId;
                        $parent_share_id = $share ? $share->id : 0;
                        if (!$share) {
                            $parent_user_id = 0;
                        }
                    }
                } else {
                    $t = ShareBuyLog::find()
                        ->where(['user_id' => $order->user_id, 'goods_id' => $v['id']])
                        ->asArray()
                        ->all();
                    if ($t) {
                        $parent_user_id = max(array_column($t, 'parent_user_id'));
                        $share = Share::find()->where(['user_id' => $parent_user_id])->one();
                        if (!$share) {
                            $parent_user_id = 0;
                        }
                    }
                }

                /*$tempModel = ShareBuyLog::find()
                    ->where(['user_id' => $order->user_id, 'goods_id' => $v['id']])
                    ->orderBy('parent_user_id desc')
                    ->one();
                \Yii::error('$tempModel--->>>>');
                \Yii::error($tempModel ? json_encode($tempModel->toArray(), 256) : '$tempModel not exist');
                if ($tempModel) {
                    $parent_user_id = $tempModel->parent_user_id;
                    $parent_share_id = $tempModel->parent_share_id;
                }
                if (empty($parent_user_id)) {
                    $s = Share::find()->where(['user_id' => $userId])->one();
                    $parent_user_id = $userId;
                    $parent_share_id = $s->id;
                }*/

                \Yii::error('$parent_user_id--->>>>' . $parent_user_id);
                \Yii::error('$parent_share_id--->>>>' . $parent_share_id);
//                \Yii::error($tempModel ? json_encode($tempModel->toArray(), 256) : '$tempModel not exist');
                $p_parent_user_id = $p_parent_share_id = 0;
                if ($parent_user_id) {
                    $pModel = ShareBuyLog::find()
                        ->where(['user_id' => $userId, 'goods_id' => $v['id']])
                        ->orderBy('parent_user_id desc')
                        ->one();
                    \Yii::error('$pModel------->>>>');
                    \Yii::error($pModel ? json_encode($pModel->toArray(), 256) : '$pModel not exist');
                    if ($pModel) {
                        $p_parent_user_id = $pModel->parent_user_id;
                        $p_parent_share_id = $pModel->parent_share_id;
                    }
                }
                \Yii::error('$p_parent_user_id--->>>>' . $p_parent_user_id);
                \Yii::error('$p_parent_share_id--->>>>' . $p_parent_share_id);

                $shareBuyLogModel = new ShareBuyLog();
                $shareBuyLogModel->mall_id = $order->mall_id;
                $shareBuyLogModel->order_id = $order->id;
                $shareBuyLogModel->goods_id = $v['id'];
                $shareBuyLogModel->parent_user_id = $parent_user_id;
                $shareBuyLogModel->parent_share_id = $parent_share_id;
                $shareBuyLogModel->p_parent_user_id = $p_parent_user_id;
                $shareBuyLogModel->p_parent_share_id = $p_parent_share_id;
                $shareBuyLogModel->user_id = $order->user_id;
                $shareBuyLogModel->share_id = $s_id;
                $res = $shareBuyLogModel->save();
                \Yii::error('$shareBuyLogModel->save() res' . (int)$res);

                if ($userId) {
                    $user = UserInfo::find()->where(['user_id' => $order->user_id])->one();
                    $user->parent_id = $userId;
                    $user->junior_at = date('Y-m-d H:i:s');
                    $res = $user->save();
                    \Yii::error('user_id:' . $order->user_id . ',parent_id:' . $userId . 'res:' . (int)$res);
                }
            }
        }

        $event = new OrderEvent();
        $event->order = $order;
        $event->sender = $this;
        \Yii::$app->trigger(Order::EVENT_PAYED, $event);
        \Yii::error('trigger....');
        return true;
    }

    /**
     * 下单同时购买超级会员卡时，订单价格调整，超级会员卡订单优惠信息记录
     * @param $order
     * @param $paymentOrder
     */
    protected function setVipCardPrice(&$order, $paymentOrder)
    {
        if (floatval($order->total_pay_price) === floatval($paymentOrder->amount)) {
            \Yii::info('setVipCardPrice--->支付金额与订单一致');
            return;
        }
        $orderVipCardInfo = OrderVipCardInfo::findOne(['order_id' => $order->id]);
        if (!$orderVipCardInfo) {
            \Yii::info('setVipCardPrice--->没有找到订单与超级会员卡同时下单记录');
            return;
        }
        if (floatval($orderVipCardInfo->order_total_price) !== floatval($paymentOrder->amount)) {
            \Yii::info('setVipCardPrice--->支付金额与超级会员卡记录金额不一致');
            return;
        }
        $discount = $order->total_pay_price - $paymentOrder->amount;
        \Yii::info('setVipCardPrice--->更新订单支付金额');
        $order->total_pay_price = price_format($paymentOrder->amount);

        $vipCardDetail = VipCardDetail::findOne($orderVipCardInfo->vip_card_detail_id);
        /** @var VipCard $vipCard */
        $vipCard = CommonVip::getCommon()->getMainCard($vipCardDetail->vip_id);

        $model = new VipCardDiscount();
        $model->discount = $discount;
        $model->discount_num = $vipCard->discount;
        $model->order_id = $order->id;
        $model->order_detail_id = $vipCardDetail->id;
        $model->main_id = $vipCard->id;
        $model->main_name = $vipCard->name;
        $model->detail_id = $vipCardDetail->id;
        $model->detail_name = $vipCardDetail->name;
        if (!$model->save()) {
            \Yii::error((new Model())->getErrorMsg($model));
        }
    }

    private function isFenxiao($order)
    {
        $ids = OrderDetail::findAll(['order_id' => $order->id]);
        $ids2 = Goods::find()->where(['in', 'id', array_column($ids, 'goods_id')])->all();
        $ids3 = GoodsCatRelation::find()->where(['in', 'goods_warehouse_id', array_column($ids2, 'goods_warehouse_id')])->all();
        $ids4 = array_unique(array_column($ids3, 'cat_id'));
        return in_array(3, $ids4);
    }
}
